<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/3/27
 * Time: 21:06
 */
namespace app\admin\model;

use app\admin\helper\DBhelper;
use app\admin\helper\LangHelper;
use app\admin\helper\SearchHelper;
use app\admin\popo\LayData;
use think\Config;
use think\Session;
use think\Validate;

class UserM extends  BaseM
{
    protected $table = 'tb_user';
    protected $module = '用户管理';

    /*
     * rule
     * 验证data
     * @params $data
     * 新增和修改时验证
     * */
    public function validate_model($scene){
        $post = input('post.');
        $rule = [
            'username' => 'unique:user|require|alphaNum|length:6,12',
            'password' => 'require|alphaNum',
            'name' => 'require',
            'gender' => '\d+',
            'email' => '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$',
            'tel' => '^1[34578]{1}\d{9}$',
            'qq' => '\d+',
            'wchat' => 'alphaNum'
        ];
        $msg = [
            'username.require' => '__user.validata.username.require__',
            'username.alphaNum' => '__user.validata.username.alphaNum__',
            'username.length' => '__user.validata.username.length__',
            'password.require' => '__user.validata.password.require__',
            'password.alphaNum' => '__user.validata.password.alphaNum__',
            'password.length' => '__user.validata.password.length__',
            'name.require' => '__user.validata.name.require__',
            'gender' => '__user.validata.gender__',
            'email' => '__user.validata.email__',
            'tel' => '__user.validata.tel__',
            'qq' => '__user.validata.qq__',
            'wchat.alphaNum' => '__user.validata.wchat.alphaNum__'
        ];
        if ($scene=="edit"){
            if ($post['username'] == 'admin')
                $rule['username']='require|alphaNum';
            else
                $rule['username']='require|alphaNum|length:6,12';
            if (strlen($post['password']) != 32){
                $rule['password'] = 'require|alphaNum|length:6,12';
            }
        }else if ($scene=="add"){
            $msg['username.unique']='__user.validata.username.unique__';
        }
        $msg = LangHelper::convertLang($msg,'field');
        $validate = new Validate($rule, $msg);
        $result = $validate->check($post);
        if(!$result){
            return op_msg(0,$validate->getError());
        }
        return op_msg(1,'success');
    }

    /**
     * 前端search控件
     * button vale [ add edit del search export ]
     * @return mixed
     */
    public function __search(){
        $search = [
            'tag'=>['field'=>'tag','title'=>'__tag__','type'=>'input','value'=>''],
            'status'=>['field'=>'status','title'=>'__status__','type'=>'select','value'=>'function:getStatusList'],
            'created_at'=>['field'=>'created_at','title'=>'__created_at__','type'=>'date_range','value'=>'function:getMonthDateRange'],
            'button'=>['type'=>'button','value'=>['add','search','export']],
        ];
        SearchHelper::convertValue($search);
        $search['form'] = implode(',',array_keys($search));
        return LangHelper::convertLang($search,'field');
    }

    /**
     * 前端表格列
     * @return string
     */
    public function __header(){
        $header = [
            ['type'=>'checkbox'],
            ['field'=>'username','title'=>'__user.username__','width'=>120],
            ['field'=>'name','title'=>'__user.name__','width'=>80],
            ['field'=>'role_name','title'=>'__role.name__','width'=>120],
            ['field'=>'gender','title'=>'__user.gender__','width'=>60,'style'=>'text-align:center'],
            ['field'=>'qq','title'=>'QQ','width'=>150],
            ['field'=>'wchat','title'=>'__user.wchat__','width'=>150],
            ['field'=>'tel','title'=>'__user.tel__','width'=>150],
            ['field'=>'email','title'=>'__user.email__','width'=>160],
            ['field'=>'updated_at','title'=>'__updated_at__','width'=>150],
            ['field'=>'status','title'=>'__status__','width'=>80,'style'=>'text-align:center'],
            ['field'=>'op','title'=>'__op__','toolbar'=>'#operate']
        ];
        return json_encode(LangHelper::convertLang($header,'field'));
    }

    /*
     * 列表
     * */
   public function listData(){
       $page=input("post.page/d");
       $limit=input("post.limit/d");
       $tag=input("post.tag/s");
       $time=input("post.created_at/s");
       $start = strtotime(explode(' - ',$time)[0]);
       $end = strtotime(explode(' - ',$time)[1]);

       $where = [
           'a.username|a.name|a.qq|a.wchat|a.tel|a.email'=>['like',"%".$tag."%"],
           'a.created_at'=>['between', [$start, $end+86399]]
       ];
       $status=input("post.status/d");
       if ($status>0) {
           $where['a.status'] = $status;
       }

       //非admin用户不能看到admin账号信息
       if (Session::get("username") != 'admin') {
           $where['a.username'] =  array('<>','admin');
       }

       $log = [
           'op_uid' => Session::get('username'),
           'op_module' => $this->module,
           'op_type' => 'search',
           'op_origin' => $this->table,
           'op_data' => json_encode($where,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
           'op_ip' => getIP(),
       ];
       //export逻辑
       if (input("post.export/b")) {
           $header = json_decode($this->__header(),true);
           $column = [];
           foreach ($header as $v) {
               if (!isset($v['field']) || $v['field'] == 'op' || $v['field'] == 'role_name')
                   continue;
               $column[] = 'a.'.$v['field'];
           }
           $column = implode(',',$column);
           $export_data = $this->alias('a')->field($column.',b.name role_name')
               ->join('tb_role b','a.role_id = b.role_id','left')
               ->where($where)->order('a.id desc')->select()->toArray();
           $log['op_type'] = 'export';
           $log['op_data'] = json_encode($header,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
           $log['op_sql'] = $this->getLastSql();
           LogsM::add($log);
           pr_log($log,'operate');
           export('用户列表',$export_data,$header);
       }
       $resp = new LayData();
       $resp->count = $this->alias('a')->where($where)->count();
       $resp->data = $this->alias('a')->field('a.*,b.name role_name')
           ->join('tb_role b','a.role_id = b.role_id','left')
           ->where($where)->order('a.id desc')->page($page,$limit)->select();
       $resp->extra_data = Config::get('app_debug')?self::getLastSql():'';
       $log['op_sql'] = $this->getLastSql();
       LogsM::add($log);
       pr_log($log,'operate');
       return $resp;
   }

    /*
     * 新增
     * */
    public function add(){
        $data=input('post.');
        unset($data['method']);
        $data['password']=md5($data['password']);
        $data['created_at']=time();
        $data['updated_at']=time();
        $re = $this->save($data);
        $last_sql = Config::get('app_debug')?self::getLastSql():'';
        if($re){
            $log = [
                'op_uid' => Session::get('username'),
                'op_module' => $this->module,
                'op_type' => 'add',
                'op_origin' => $this->table,
                'op_data' => $data['username'],
                'op_ip' => getIP(),
                'op_sql' => $this->getLastSql(),
            ];
            LogsM::add($log);
            pr_log($log,'operate');
            return op_success($last_sql);
        }
        return op_fail($last_sql);
    }

    /*
     * 修改
     * */
    public function edit(){
        $data=input('post.');
        $id=$data['id'];
        if (strlen($data['password']) != 32)
            $data['password']=md5($data['password']);
        //admin用户不允许修改角色和状态
        if ($data['username']=='admin'){
            unset($data['role_id']);
            unset($data['status']);
        }
        //username不允许修改
        unset($data['username']);
        unset($data['method']);
        //只修改变化字段
        $origin = $this->getById($id)->toArray();
        $data = DBhelper::getChangeData($data,$origin);
        if (!empty($data)){

            $data['updated_at']=time();
            $re = $this->where('id',$id)->update($data);
            $last_sql = Config::get('app_debug')?$this->getLastSql():'';
            if($re){
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'edit',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($data,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => $this->getLastSql(),
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
            return op_fail($last_sql);
        }
        return op_nochange();
    }

    /*
     * 删除
     * */
    public function del(){
        $ids=input('post.ids/a');
        $op_name=[];
        foreach ($ids as $id){
            $username = $this->getById($id)->toArray()['username'];
            if ($username != 'admin')
                array_push($op_name,$username);
        }
        if (!empty($op_name)) {
            $re = $this->destroy($ids);
            $last_sql = Config::get('app_debug')?self::getLastSql():'';
            if ($re){
                $log = [
                    'op_uid' => Session::get('username'),
                    'op_module' => $this->module,
                    'op_type' => 'delete',
                    'op_origin' => $this->table,
                    'op_data' => json_encode($op_name,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                    'op_ip' => getIP(),
                    'op_sql' => $this->getLastSql(),
                ];
                LogsM::add($log);
                pr_log($log,'operate');
                return op_success($last_sql);
            }
            return op_fail($last_sql);
        }
        return op_superadmin();
    }

    /*
     * 根据MAP获取信息
     * */
    public function getOneByMap($map){
        return $this->where($map)->find();
    }

}